package com.gz.common;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.gz.common.model.Receivingaddress;
import com.gz.common.model.User;

public class ReceivingAddressService {
	private static ReceivingAddressService service;

	private ReceivingAddressService() {
	}

	public static ReceivingAddressService getService() {
		if (service == null) {
			service = new ReceivingAddressService();
		}
		return service;
	}

	// 获取当前用户的所有收货信息
//	public User getAddressListByUserTest(Integer userId) {
//		//查出该用户信息
//		User user = UserService.getService().findUserId(userId);
//		//判断该用户是否存在
//		if (user != null) {
//			String sql = "select r.*,\r\n" + "(select `name` from tb_region where id=r.Provinceid) as 'Province',\r\n"
//					+ "(select `name` from tb_region where id=r.Cityid) as 'City',\r\n"
//					+ "(select `name` from tb_region where id=r.Areaid) as 'Area',\r\n"
//					+ "(select `name` from tb_region where id=r.streetid) as 'street'\r\n"
//					+ "from receivingaddress as r \r\n" + "where Userid=?";
//			//如果用户存在查出该用户的所有收货地址信息
//			List<Receivingaddress> receivingaddressList = Receivingaddress.dao.find(sql, userId);
//			if (receivingaddressList.size() > 0) {
//				//把所有收货地址转成json格式
//				String JsonReceivingaddressList = JSON.toJSONString(receivingaddressList);
//				System.out.println("地址转json结果：=" + JsonReceivingaddressList);
//				//判断该用户是否有收货地址或者收货地址是否有变？
//				if(user.getAddress()==null||!user.getAddress().equals(JsonReceivingaddressList)) {
//					user.setAddress(JsonReceivingaddressList);
//					//没有或者地址有变更新数据库
//					user.update();
//				}
//			}
//		}
//		return user;
//	}

	// 获得当前用户所有地址信息
	public List<Receivingaddress> getAddressListByUser(Integer userId) {
		String sql = "select r.*,\r\n" + "(select `name` from tb_region where id=r.Provinceid) as 'Province',\r\n"
				+ "(select `name` from tb_region where id=r.Cityid) as 'City',\r\n"
				+ "(select `name` from tb_region where id=r.Areaid) as 'Area',\r\n"
				+ "(select `name` from tb_region where id=r.streetid) as 'street'\r\n"
				+ "from receivingaddress as r \r\n" + "where Userid=?";
		return Receivingaddress.dao.find(sql, userId);
	}

	// 新增收货地址
	public boolean addReceivingaddress(Receivingaddress receivingaddress) {

		return receivingaddress.save();
	}
}
